package com.zbs.simbot.events;

import com.zbs.simbot.config.SimBotConfig;
import com.zbs.simbot.enums.MsgType;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import love.forte.simbot.ID;
import love.forte.simbot.Identifies;
import love.forte.simbot.bot.Bot;
import love.forte.simbot.component.mirai.event.MiraiMemberMessageEvent;
import love.forte.simbot.definition.*;
import love.forte.simbot.event.FriendMessageEvent;
import love.forte.simbot.event.GroupMessageEvent;
import love.forte.simbot.event.MessageEvent;
import love.forte.simbot.message.*;
import love.forte.simbot.resources.Resource;

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Paths;
import java.text.MessageFormat;

@Getter
@Slf4j
public class BaseMsgEvent {

    private final MessageEvent event;
    private final ReceivedMessageContent messageContent;
    private final Bot bot;
    private final String msg;
    private final StringBuilder fullMsg;
    private final Long userId;
    private UserInfo user;
    private Group group;
    private final boolean authorMasterQQ;
    private boolean atBot = false;
    private ChatRoom chatRoom;
    private Contact contact;
    private MsgType msgType;


    public BaseMsgEvent(MessageEvent event) {
        this.initMessageEvent(event);
        this.user = this.getUser();
        this.userId = Long.parseLong(this.getUser().getId().toString());
        this.fullMsg = new StringBuilder();
        this.event = event;
        this.messageContent = event.getMessageContent();
        this.bot = event.getBot();
        this.msg = event.getMessageContent().getPlainText();
        this.authorMasterQQ = SimBotConfig.masterQq.contains(this.userId);
        this.getFullMsg(event);
    }


    private void initMessageEvent(MessageEvent event) {
        // 好友消息
        if (event instanceof FriendMessageEvent e) {
            this.user = e.getUser();
            this.contact = e.getUser();
            msgType = MsgType.FRIEND;
        }

        // 群私聊消息
        if (event instanceof MiraiMemberMessageEvent e) {
            this.user = e.getUser();
            this.chatRoom = e.getUser().getGroup();
            msgType = MsgType.PRIVATE;
        }

        // 群消息
        if (event instanceof GroupMessageEvent e) {
            this.user = e.getAuthor();
            this.group = e.getGroup();
            this.contact = e.getAuthor();
            this.chatRoom = e.getGroup();
            msgType = MsgType.GROUP;
        }
    }

    /**
     * 阻塞回复消息
     * @param txt 消息内容
     */
    public void reply(String txt) {
        this.builder().text(txt).replyBlocking();
    }

    /**
     * 阻塞回复消息并且@这个人
     * @param txt 内容
     */
    public void replyAt(String txt) {
        this.builder().at().text(txt).replyBlocking();
    }

    /**
     * 回复消息 并且@ userId 这个人
     * @param userId 用户ID
     * @param txt 内容
     */
    public void reply(Long userId, String txt) {
        this.builder().at(userId, txt).replyBlocking();
    }

    /**
     * 回复消息 并且@ userId 这个人
     * @param userId 用户ID
     * @param txt 内容
     */
    public void reply(ID userId, String txt) {
        this.builder().at(userId).text(txt).replyBlocking();
    }

    /**
     * 发送消息
     * @param txt 内容
     */
    public void send(String txt) {
        this.builder().text(txt).sendBlocking();
    }

    /**
     * 发送消息并且 @ 这个人
     * @param txt 内容
     */
    public void sendAt(String txt) {
        this.builder().at().text(txt).sendBlocking();
    }

    /**
     * @ 所有人 发送消息
     * @param txt 内容
     */
    public void sendAll(String txt) {
        this.builder().atAll(txt).sendBlocking();
    }

    /**
     * @ 某个人 发送消息
     * @param userId 用户ID
     * @param txt 内容
     */
    public void send(ID userId, String txt) {
        this.builder().at(userId).text(txt).sendBlocking();
    }

    /**
     * @ 某个人 发送消息
     * @param userId 用户ID
     * @param txt 内容
     */
    public void send(Long userId, String txt) {
        this.builder().at(userId).text(txt).sendBlocking();
    }

    /**
     * 获取完整的消息内容
     * @return 完整的消息内容
     */
    public String getFullMsg() {
        return fullMsg.toString();
    }


    private void getFullMsg(MessageEvent event) {
        Messages msg = event.getMessageContent().getMessages();
        for (Message.Element<?> element : msg) {
            if (element instanceof At && event instanceof GroupMessageEvent e) {
                ID targetId = ((At) element).getTarget();
                GroupMember targetMember = e.getGroup().getMember(targetId);
                if (targetId.toString().equals(event.getBot().getId().toString())) {
                    atBot = true;
                }
                if (targetMember != null) {
                    fullMsg.append(MessageFormat.format("@{0}({1})", targetMember.getNickOrUsername(), targetMember.getId()));
                }
            }
            if (element instanceof Text) {
                fullMsg.append(MessageFormat.format("{0}", ((Text) element).getText()));
            }
            if (element instanceof Image<?> image) {
                fullMsg.append(MessageFormat.format("[图片:{0}]", image.getResource().getName()));
            }
            if (element instanceof Face) {
                fullMsg.append(MessageFormat.format("[Face:{0}]", ((Face) element).getId()));
            }
        }

    }

    public MsgBuilder builder() {
        return new MsgBuilder(msgType, contact, chatRoom, event, this.userId);
    }

    public static class MsgBuilder {
        private final MessageEvent event;
        private final MessagesBuilder builder;
        private final Long userId;
        private final MsgType msgType;

        private final ChatRoom chatRoom;
        private final Contact contact;


        public MsgBuilder(MsgType msgType, Contact contact, ChatRoom chatRoom, MessageEvent event, Long userId) {
            this.msgType = msgType;
            this.event = event;
            this.contact = contact;
            this.chatRoom = chatRoom;
            this.userId = userId;
            builder = new MessagesBuilder();
        }

        public MsgBuilder text(String text) {
            builder.append(text);
            return this;
        }

        public MsgBuilder imagePath(String path) {
            builder.image(Resource.of(Paths.get(path)));
            return this;
        }

        public MsgBuilder image(byte[] bytes, String name) {
            builder.image(Resource.of(bytes, name));
            return this;
        }

        public MsgBuilder imageUrl(String url) {
            try {
                URL u = new URL(url);
                builder.image(Resource.of(u));
            } catch (MalformedURLException e) {
                log.error("图片转换异常", e);
                this.text("图片转换异常");
            }
            return this;
        }

        public MsgBuilder atAll(String txt) {
            this.atAll().text(txt);
            return this;
        }

        public MsgBuilder atAll() {
            builder.append(AtAll.INSTANCE);
            return this;
        }

        public MsgBuilder at(ID userId) {
            builder.append(new At(userId));
            return this;
        }

        public MsgBuilder at(Long userId) {
            builder.append(new At(Identifies.ID(userId)));
            return this;
        }

        public MsgBuilder at(Long userId, String text) {
            this.at(userId).text(text);
            return this;
        }

        public MsgBuilder at() {
            if (this.userId != null) {
                builder.append(new At(Identifies.ID(this.userId)));
            }
            return this;
        }

        /**
         * 异步回复消息
         */
        public void replyAsync() {
            this.event.replyAsync(builder.build());
        }

        /**
         * 阻塞回复消息
         */
        public void replyBlocking() {
            this.event.replyBlocking(builder.build());
        }

        /**
         * 异步发送消息
         */
        public void sendAsync() {
            if (msgType.equals(MsgType.FRIEND)) {
                this.contact.sendAsync(builder.build());
            } else if (msgType.equals(MsgType.GROUP)) {
                this.chatRoom.sendAsync(builder.build());
            } else if (msgType.equals(MsgType.PRIVATE)) {
                ((MiraiMemberMessageEvent) event).sendAsync(builder.build());
            }
        }

        /**
         * 异步发送群私聊消息
         */
        public void sendGroupPrivateAsync() {
            this.contact.sendAsync(builder.build());
        }

        /**
         * 阻塞发送群私聊消息
         */
        public void sendGroupPrivateBlocking() {
            this.contact.sendBlocking(builder.build());
        }

        /**
         * 阻塞式发送消息
         */
        public void sendBlocking() {
            if (msgType.equals(MsgType.FRIEND)) {
                this.contact.sendBlocking(builder.build());
            } else if (msgType.equals(MsgType.GROUP)) {
                this.chatRoom.sendBlocking(builder.build());
            } else if (msgType.equals(MsgType.PRIVATE)) {
                ((MiraiMemberMessageEvent) event).sendBlocking(builder.build());
            }
        }

    }
}
